<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form isheader" v-if="headerShow" style="margin-top: 20px;">
                <div>
                    <a-form size="small" :model="pageData" layout="inline">
                        <a-form-item label="筛选时间">
                            <a-date-picker  popup-container="html"  class="bacClass" style="width: 200px;" @select="onSelect" @clear="onClear"
                                v-model="pageData.dropDownData.startDate" />至
                            <a-date-picker  popup-container="html"  class="bacClass" style="width: 200px;" @select="onSelect" @clear="onClear"
                                v-model="pageData.dropDownData.endDate" />
                        </a-form-item>
                    </a-form>
                </div>
                <div>
                    <Toolbar :items="['查询', '导出']" @select="selectHandler" @export="exports"></Toolbar>
                </div>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
        </template>
        <template #pageTabel>
            <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:99%;width: 100%;z-index:999 ;">
                <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressDragLeaveHidesColumns="true"
                    :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady"
                    style="height:99%" :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="table.dataList"
                    :columnDefs="tc" :localeText="localeText1"  @columnResized="onColumnResized"
                    @columnMoved="onColumnMoved"></AgGridVuesCopys>
            </a-spin>
        </template>
        <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
            @change="PageSize" @page-size-change="change1" style="justify-content: center" :page-size="pagination.pageSize"
            :current="pagination.page" />
    </pageTabelLayout>
</template>

<script lang="ts">
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table';
import emitter from "@/hooks/useEventBus";
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue';
import { Form, Message, Modal } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { String } from 'lodash';
import { baseURL } from '@/api/axios.config'
import axios from "axios";
import usePermission from '@/store/modules/permission'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import validate from "@/hooks/useValidate";
import filedownload from 'js-file-download'
import dayjs from 'dayjs'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'

interface DyeingVatEfficient {
    "id": any
    "remark": any
}

export default {
    name: "DyeingVatEfficient",
    setup() {
        const total = ref(0);
        const page = ref(1);
        const size = ref(10);

        function PageSize(val: any) {
            pagination.page = val
            doRefresh();
        }

        function change1(val: any) {
            pagination.pageSize = val
            doRefresh();
        }

        function doRefresh() {
            pageData.pageLoading = true
            var startDate = pageData.dropDownData.startDate
            var endDate = pageData.dropDownData.endDate
            let data1 = startDate
            let data2 = endDate
            var formatDate1 = new Date(startDate)
            var formatDate2 = new Date(endDate)
            if (formatDate1 > formatDate2) {
                startDate = data2 ? data2 + ' 00:00:00' : ''
                endDate = data1 ? data1 + ' 23:59:59' : ''
            } else {
                startDate = data1 ? data1 + ' 00:00:00' : ''
                endDate = data2 ? data2 + ' 23:59:59' : ''
            } 
            // updateGridState01()
            post({
                url: "/pdm/TransitInspect/selectXL",
                data: {
                    page: pagination.page,
                    size: pagination.pageSize,
                    deleteState: 0,
                    startDate: startDate,
                    endDate: endDate,
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        table.handleSuccess(data.list);
                        gridOption.value.setRowData(data.list);
                        total.value = data.total;
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }

        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        const tableColumns = useTableColumn([
            {
                title: "车间",
                key: "workshop",
                dataIndex: "workshop",
                width: 150
            },
            {
                title: "设备编号",
                key: "controlMachineCode",
                dataIndex: "controlMachineCode",
                width: 150
            },
            {
                title: "设备类型",
                key: "controlMachineType",
                dataIndex: "controlMachineType",
                width: 150
            },
            {
                title: "管数",
                key: "tubeType",
                dataIndex: "tubeType",
                width: 150
            },
            {
                title: "工艺时间",
                key: "craftDate",
                dataIndex: "craftDate",
                width: 150
            },
            {
                title: "实际时间",
                key: "realityDate",
                dataIndex: "realityDate",
                width: 150
            },
            {
                title: "进出缸时间",
                key: "jcgsj",
                dataIndex: "jcgsj",
                width: 150
            },
            {
                title: "剪办对色",
                key: "jbds",
                dataIndex: "jbds",
                width: 150
            },
            {
                title: "超时时间",
                key: "cssj",
                dataIndex: "cssj",
                width: 150
            },
            {
                title: "空缸时间",
                key: "kgsj",
                dataIndex: "kgsj",
                width: 150
            },
            {
                title: "有效率%",
                key: "yxl",
                dataIndex: "yxl",
                width: 150
            },
            {
                title: "机台运转率%",
                key: "jtyzl",
                dataIndex: "jtyzl",
                width: 150
            },
            {
                title: "机台有效率%",
                key: "jtyzl",
                dataIndex: "jtyzl",
                width: 150
            },
        ]);


        let tc: any[] = tableColumns.map((o) => {
            let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed']
            }
            return obj
        })



        let a = [{
            showRowGroup: 'hide_def',
            "headerName": "",
            "checkboxSelection": true,
            "headerCheckboxSelection": true,
            "pinned": "left",
            "width": 50,
            resizable: false,
            filter: false,
            sortable: false,
            minWidth: 50,
            maxWidth: 50,
            lockPosition: "left",
        }]
        tc = a.concat(tc)

        const pageData = reactive<{
            dropDownData: any,
            pageLoading: boolean,
        }>({
            dropDownData: {
                startDate: dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
                endDate: dayjs().format('YYYY-MM-DD'),
            },
            pageLoading: false,
        });

        onMounted(() => {
            emitter.on("DyeingVatEfficient", () => {
                doRefresh();
            });
        });
        //查询
        const selectHandler = () => {
            pagination.page = 1
            doRefresh();
        }

        const dataForm = reactive<DyeingVatEfficient>({
            "id": null,
            "remark": '',
        })

        // 表格准备事件
        const gridOption = ref()
        const colState = ref()
        const gridReady = (params: any) => {
            gridOption.value = params.api
            colState.value = params.columnApi
        }

        //导出
        const exports = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选数据!');
                return
            } else {
                let idList: any = []
                gridOption.value.getSelectedRows().forEach(function (o: any) {
                    idList.push(o['controlMachineCode'])
                })
                //将表头拼接出来
                let head = "<th>车间</th><th>设备编号</th><th>设备类型</th><th>管数</th><th>工艺时间</th><th>实际时间</th><th>进出缸时间</th><th>剪办对色</th><th>超时时间</th><th>空缸时间</th><th>有效率%</th><th>机台运转率%</th><th>机台有效率%</th>"
                //拿到当前表格数据与勾选的行做筛选
                let nowRow = table.dataList.filter(function (o: any) {
                    return (gridOption.value.getSelectedRows().map((o: any) => { return o.controlMachineCode }).indexOf(o['controlMachineCode']) !== -1)
                })
                let body = "";
                nowRow.forEach(function (o) {
                    body += "<tr><td>" + (o["workshop"] === undefined ? '': o["workshop"]) + "</td>";
                    body += "<td>" + (o["controlMachineCode"] === undefined ? '': o["controlMachineCode"]) + "</td>";
                    body += "<td>" + (o["controlMachineType"] === undefined ? '': o["controlMachineType"]) + "</td>";
                    body += "<td>" + (o["tubeType"] === undefined ? '': o["tubeType"]) + "</td>";
                    body += "<td>" + (o["craftDate"] === undefined ? '': o["craftDate"]) + "</td>";
                    body += "<td>" + (o["realityDate"] === undefined ? '': o["realityDate"]) + "</td>";
                    body += "<td>" + (o["jcgsj"] === undefined ? '': o["jcgsj"]) + "</td>";
                    body += "<td>" + (o["jbds"] === undefined ? '': o["jbds"]) + "</td>";
                    body += "<td>" + (o["cssj"] === undefined ? '': o["cssj"]) + "</td>";
                    body += "<td>" + (o["kgsj"] === undefined ? '': o["kgsj"]) + "</td>";
                    body += "<td>" + (o["yxl"] === undefined ? '': o["yxl"]) + "</td>";
                    body += "<td>" + (o["jtyzl"] === undefined ? '': o["jtyzl"]) + "</td>";
                    body += "<td>" + (o["jtyzl"] === undefined ? '': o["jtyzl"]) + "</td>";
                    body += "</tr>";
                })
                tableToXlsx(head, '染缸有效率查询', body)
            }
        }

        function tableToXlsx(head: any, filename: any, body: any) {
            const uri = 'data:application/vnd.ms-excel;base64,',
                template = `<html>
                               <head><meta charset="UTF-8"></head>
                               <body><table border="1"><tr>${head}</tr>${body}</table></body>
                            </html>`
            const a = document.createElement('a')
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
            a.download = filename
            a.click()
            document.removeChild(a)
        }
        const handleChange = (_data: any) => {
            table.handleSuccess(_data);
        }
        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
            width:150
        }

        const headerShow = ref<boolean>(true)
        const localeText1: any = ref(localeText)
        const pagingList1: any = ref(pagingList)
        const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('DyeingVatEfficient01', gridOption, colState, tc)
        const onColumnMoved = () => {
            saveGridState01()
        }
        const onColumnResized = () => {
            saveGridState01()
        }
        return {
            saveOrUpdateGridState01,
            saveGridState01,
            updateGridState01,
            onColumnMoved,
            onColumnResized,
            colState,
            pagingList1,
            localeText1,
            defaultColDef,
            tc,
            gridOption,
            gridReady,
            total,
            PageSize,
            change1,
            page,
            size,
            dataForm,
            selectedRowKeys,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            selectHandler,
            exports,
            headerShow,
            handleChange,
            onSelect(dateString: any, date: any) {
                pageData.dropDownData = {
                    startDate: dateString[0],
                    endDate: dateString[1],
                }
            },
            onClear() {
                pageData.dropDownData = {}
            },
        };
    },
    components: { Toolbar,  }
}
</script>
<style scoped lang="less"></style>